package club.kingyin.easycache.proxy;

import club.kingyin.easycache.cache.ProxyMethodCache;
import club.kingyin.easycache.key.AbstractEasyCacheKey;
import club.kingyin.easycache.method.CacheMethod;
import club.kingyin.easycache.proxy.adapter.AbstractEasyCacheMethod;
import club.kingyin.easycache.proxy.adapter.CacheMethodKeyAdapter;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.reflect.MethodSignature;

import java.lang.reflect.Method;
import java.util.function.Function;

public class PointEasyCache extends AbstractEasyCacheMethod<ProceedingJoinPoint> {

    private Function<AbstractEasyCacheKey,Void> init;

    public PointEasyCache(ProxyMethodCache cache, CacheMethodKeyAdapter adapter, Function<AbstractEasyCacheKey,Void> init) {
        super(cache, adapter);
        this.init = init;
    }

    public PointEasyCache(ProxyMethodCache cache, CacheMethodKeyAdapter adapter) {
        super(cache, adapter);
    }

    @Override
    protected CacheMethod adaptation(ProceedingJoinPoint target) {
        MethodSignature signature = (MethodSignature) target.getSignature();
        return new CacheMethod() {
            @Override
            public Method getMethod() {
                return signature.getMethod();
            }

            @Override
            public Object proceed() throws Throwable {
                return target.proceed();
            }

            @Override
            public Object[] getArguments() {
                return target.getArgs();
            }
        };
    }

    @Override
    protected void init(AbstractEasyCacheKey cacheKey) {
        if (init == null)
            super.init(cacheKey);
        else init.apply(cacheKey);
    }
}
